export class SSEParser {
  private onMessage: (data: any) => void;
  private buffer: string = "";

  constructor(onMessage: (data: any) => void) {
    this.onMessage = onMessage;
  }

  feed(chunk: string) {
    this.buffer += chunk;
    const lines = this.buffer.split("\n");
    this.buffer = lines.pop() || "";

    lines.forEach(line => {
      if (line.startsWith("data:")) {
        const rawData = line.replace("data:", "").trim();
        if (rawData === "") return; // 忽略空行
        try {
          const data = JSON.parse(rawData);
          if (!data.status) this.onMessage(data); // 忽略状态消息
        } catch (e) {
          console.error("SSE数据解析失败:", e);
        }
      }
    });
  }
}
